package com.hll.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * Created by CGL on 2017-06-24 14:18:46.
 */
public abstract class BaseModel<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    public BaseModel() {
    }

    public Map<String, Object> toMap() {
        return this.toJSONObject();
    }

    public Map<String, Object> toMap(boolean ordered) {
        return this.toJSONObject(ordered);
    }

    public JSONObject toJSONObject() {
        return this.toJSONObject(false);
    }

    public JSONObject toJSONObject(boolean ordered) {
        JSONObject jsonObject = new JSONObject(ordered);
        Field[] fields = this.getClass().getDeclaredFields();
        Field[] var7 = fields;
        int var6 = fields.length;

        for(int var5 = 0; var5 < var6; ++var5) {
            Field field = var7[var5];

            try {
                if(!field.getName().equals("serialVersionUID")) {
                    field.setAccessible(true);
                    Object e = field.get(this);
                    jsonObject.put(field.getName(), e);
                }
            } catch (Exception var9) {
                throw new RuntimeException("convert JsonObject error", var9);
            }
        }

        return jsonObject;
    }

    public T cloneBean() {
        return (T)JSON.toJavaObject(this.toJSONObject(), this.getClass());
    }

    public T populate(Map map) {
        JSONObject jsonObject = this.toJSONObject();
        jsonObject.putAll(map);
        return (T)JSON.toJavaObject(jsonObject, this.getClass());
    }

    public String toString() {
        return JSON.toJSONString(this);
    }
}
